import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:management/model/visitor_model.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:management/utils/custom_router.dart';
import 'package:management/views/visitor/query/delete_record_by_time.dart';
import 'package:management/views/visitor/query/record_details.dart';

///查询结果页面
class QueryResult extends StatefulWidget {
  final List<Visitor>? visitorRecords;

  const QueryResult({Key? key, this.visitorRecords}) : super(key: key);

  @override
  _QueryResultState createState() => _QueryResultState();
}

class _QueryResultState extends State<QueryResult> {
  List<Visitor>? visitorRecords;
  bool isDeleteAll = false;

  @override
  initState() {
    SystemChrome.setEnabledSystemUIOverlays([]);
    super.initState();
  }

  AppBar _buildAppBar() => AppBar(
        leading: IconButton(
          icon: Icon(Icons.arrow_back),
          iconSize: 35,
          onPressed: () => Navigator.of(context).pop(),
        ),
        title: Text(
          "查询结果",
          style: TextStyle(fontWeight: FontWeight.bold, fontSize: 25.sp),
        ),
        centerTitle: true,
        backgroundColor: Colors.blue,
        actions: [
          SpUtil.getString("userName") == "admin"
              ? CustomPopupMenuButton(
                  onDeleteAll: onDeleteAll,
                )
              : SizedBox()
        ],
      );

  onDeleteAll() {
    VisitorProvider.provider.deleteAll();
    setState(() {
      isDeleteAll = true;
    });
  }

  //访客姓名 性别 来访事项 被访部门 被访人
  Widget _buildBody() => Container(
        width: 1.sw,
        height: 1.sh,
        color: Colors.black12,
        padding: EdgeInsets.all(10.w),
        child: Container(
          width: 0.9.sw,
          height: 0.9.sw,
          padding: EdgeInsets.all(50.w),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(12.w),
            border: Border.all(color: Colors.grey, width: 2.w),
            color: Colors.white,
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              SizedBox(
                height: 30,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Padding(
                      padding: EdgeInsets.only(left: 170),
                      child: Text(
                        "访客姓名",
                        style: TextStyle(
                            fontWeight: FontWeight.bold, fontSize: 22.sp),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(left: 185),
                      child: Text(
                        "性别",
                        style: TextStyle(
                            fontWeight: FontWeight.bold, fontSize: 22.sp),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(left: 210),
                      child: Text(
                        "来访事项",
                        style: TextStyle(
                            fontWeight: FontWeight.bold, fontSize: 22.sp),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(left: 200),
                      child: Text(
                        "被访部门",
                        style: TextStyle(
                            fontWeight: FontWeight.bold, fontSize: 22.sp),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(left: 190),
                      child: Text(
                        "被访人",
                        style: TextStyle(
                            fontWeight: FontWeight.bold, fontSize: 22.sp),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(left: 220),
                      child: Text(
                        "登记时间",
                        style: TextStyle(
                            fontWeight: FontWeight.bold, fontSize: 22.sp),
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(
                child: Divider(
                  color: Colors.black,
                ),
              ),
              Expanded(
                  flex: 6,
                  child: SeparatedListView(
                    visitorRecords: visitorRecords,
                    onItemClick: () => setState(() {}),
                    onItemLongClick: (index) {
                      // Fluttertoast.showToast(msg: "$index");
                      if (SpUtil.getString("userName") == "admin") {
                        VisitorProvider.provider.delete(visitorRecords![index]);
                        Fluttertoast.showToast(msg: "删除成功");
                        setState(() {
                          visitorRecords!.removeAt(index);
                        });
                      }
                    },
                  )),
              Expanded(
                flex: 1,
                child: visitorRecords == null || visitorRecords!.isEmpty
                    ? Container()
                    : Container(
                        height: 20,
                        width: 240,
                        alignment: Alignment.center,
                        child: Text(
                          "共有${visitorRecords!.length}条记录",
                          style: TextStyle(fontSize: 22),
                        ),
                      ),
              )
            ],
          ),
        ),
      );

  @override
  Widget build(BuildContext context) {
    // visitorRecords = ModalRoute.of(context).settings.arguments;
    visitorRecords = widget.visitorRecords;
    if (isDeleteAll) {
      visitorRecords = [];
    }
    return Scaffold(
      appBar: _buildAppBar(),
      body: _buildBody(),
    );
  }
}

@deprecated
class VisitorRecordsDataTableSource extends DataTableSource {
  final List<Visitor> visitorRecords;

  VisitorRecordsDataTableSource(this.visitorRecords);

  @override
  DataRow getRow(int index) {
    return DataRow.byIndex(index: index, cells: [
      // DataCell(child),
    ]);
  }

  @override
  // TODO: implement isRowCountApproximate
  bool get isRowCountApproximate => throw UnimplementedError();

  @override
  // TODO: implement rowCount
  int get rowCount => throw UnimplementedError();

  @override
  // TODO: implement selectedRowCount
  int get selectedRowCount => throw UnimplementedError();
}

class CustomPopupMenuButton extends StatelessWidget {
  final VoidCallback onDeleteAll;

  CustomPopupMenuButton({
    required this.onDeleteAll,
  });

  final map = {"删除所有记录": Icons.delete_forever, "按时间线删除": Icons.delete};

  @override
  Widget build(BuildContext context) {
    return PopupMenuButton(
      iconSize: 35,
      itemBuilder: (context) => buildItems(),
      offset: Offset(0, 50),
      color: Color(0xffF4FFFA),
      elevation: 1,
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(20),
              bottomRight: Radius.circular(20),
              topRight: Radius.circular(5),
              bottomLeft: Radius.circular(5))),
      onSelected: (e) {
        if (e == "删除所有记录") {
          showDialog(
              context: context,
              builder: (context) => _buildDeleteAllDialog(context));
        }
        if (e == "按时间线删除") {
          // Navigator.of(context).pushNamed('/DeleteRecordByTime');

          Navigator.push(context, SlideRoute(DeleteRecordByTime()));
        }
      },
    );
  }

  buildItems() {
    return map.keys
        .map((e) => PopupMenuItem(
              value: e,
              child:
                  Wrap(spacing: 10, alignment: WrapAlignment.center, children: [
                Icon(
                  map[e],
                  color: Colors.blue,
                ),
                Text(e)
              ]),
            ))
        .toList();
  }

  Widget _buildDeleteAllDialog(BuildContext context) => Dialog(
        backgroundColor: Colors.white,
        elevation: 5,
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.all(Radius.circular(10))),
        child: Container(
          width: 50,
          child: DeleteDialog(
            onDelete: onDeleteAll,
          ),
        ),
      );
}

class DeleteDialog extends StatelessWidget {
  final VoidCallback onDelete;

  const DeleteDialog({Key? key, required this.onDelete}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          _buildBar(context),
          _buildTitle(),
          _buildContent(),
          _buildFooter(context),
        ],
      ),
    );
  }

  Widget _buildTitle() {
    return Text(
      '警告',
      style: TextStyle(color: Colors.red, fontSize: 24),
    );
  }

  Widget _buildContent() {
    return Padding(
      padding: const EdgeInsets.all(15.0),
      child: Text(
        '点击确定按钮将会删除所有记录,' '  确定要这样做吗?',
        style: TextStyle(color: Colors.red, fontSize: 16),
        textAlign: TextAlign.center,
      ),
    );
  }

  Widget _buildFooter(context) {
    return Padding(
      padding:
          const EdgeInsets.only(bottom: 15.0, top: 10, left: 10, right: 10),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          InkWell(
            onTap: () {
              onDelete();
              Navigator.of(context).pop();
            },
            child: Container(
              alignment: Alignment.center,
              height: 40,
              width: 100,
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.all(Radius.circular(30)),
                  color: Color(0xff73D1EE)),
              child: Text('确定',
                  style: TextStyle(color: Colors.white, fontSize: 16)),
            ),
          ),
          InkWell(
            onTap: () => Navigator.of(context).pop(),
            child: Container(
              alignment: Alignment.center,
              height: 40,
              width: 100,
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.all(Radius.circular(30)),
                  color: Colors.orangeAccent),
              child: Text('取消',
                  style: TextStyle(color: Colors.white, fontSize: 16)),
            ),
          )
        ],
      ),
    );
  }

  _buildBar(context) => Container(
        height: 30,
        alignment: Alignment.centerRight,
        margin: EdgeInsets.only(right: 10, top: 5),
        child: InkWell(
          onTap: () => Navigator.of(context).pop(),
          child: Icon(
            Icons.close,
            color: Color(0xff82CAE3),
          ),
        ),
      );
}

class SeparatedListView extends StatelessWidget {
  final List<Visitor>? visitorRecords;
  final VoidCallback onItemClick;
  final OnItemLongClickListener onItemLongClick;

  const SeparatedListView(
      {Key? key,
      required this.visitorRecords,
      required this.onItemClick,
      required this.onItemLongClick})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    if (visitorRecords == null || visitorRecords!.isEmpty)
      return Container(
        width: 100,
        height: 30,
        child: Center(child: Text("没有记录")),
      );
    return Container(
      decoration: BoxDecoration(),
      height: 800.h,
      child: Scrollbar(
        thickness: 15,
        showTrackOnHover: true,
        hoverThickness: 25,
        isAlwaysShown: false,
        child: ListView.builder(
          itemBuilder: (context, index) => _buildItem(context, index),
          // separatorBuilder: (context, index) => Divider(
          //   thickness: 0,
          //   height: 0,
          // ),
          itemCount: visitorRecords == null ? 1 : visitorRecords!.length,
        ),
      ),
    );
  }

  _buildItem(BuildContext context, int index) {
    Visitor visitor = visitorRecords![index];
    return RecordItem(
      visitor: visitor,
      index: index,
      onTap: onItemClick,
      onLongPress: onItemLongClick,
    );
  }
}

typedef OnItemLongClickListener = void Function(int index);

class RecordItem extends StatelessWidget {
  final Visitor visitor;
  final int index;
  final VoidCallback onTap;
  final OnItemLongClickListener onLongPress;

  const RecordItem(
      {Key? key,
      required this.visitor,
      required this.index,
      required this.onTap,
      required this.onLongPress})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: 3,
      child: InkWell(
        child: Container(
          height: 60.h,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Container(
                alignment: Alignment.center,
                width: 120,
                child: Text(
                  "${index + 1}",
                  style: TextStyle(fontSize: 22),
                ),
              ),
              Container(
                alignment: Alignment.center,
                width: 180,
                child: Text(
                  "${visitor.name}",
                  style: TextStyle(fontSize: 22),
                ),
              ),
              Container(
                alignment: Alignment.center,
                width: 330,
                child: Text(
                  "${visitor.gender}",
                  style: TextStyle(fontSize: 22),
                ),
              ),
              Container(
                alignment: Alignment.center,
                width: 220,
                child: Text(
                  "${visitor.visitingMatters == null ? "" : visitor.visitingMatters}",
                  style: TextStyle(fontSize: 22.sp),
                ),
              ),
              Container(
                alignment: Alignment.center,
                width: 350,
                child: Text(
                  "${visitor.departmentInterviewed == null ? "" : visitor.departmentInterviewed}",
                  style: TextStyle(fontSize: 22.sp),
                ),
              ),
              Container(
                alignment: Alignment.center,
                width: 185,
                child: Text(
                  "${visitor.interviewee == null ? "" : visitor.interviewee}",
                  style: TextStyle(fontSize: 22.sp),
                ),
              ),
              Container(
                alignment: Alignment.center,
                width: 400,
                child: Text(
                  "${visitor.registrationDate == null ? "" : visitor.checkInTime == null ? "" : visitor.registrationDate! + " ${visitor.checkInTime}"}",
                  style: TextStyle(fontSize: 22.sp),
                ),
              ),
            ],
          ),
        ),
        onTap: () {
          ///跳转到详细结果页面

          // Fluttertoast.showToast(msg: "${visitor.name}");
          // Navigator.of(context).pushNamed('/RecordDetails', arguments: visitor);
          Navigator.push(
              context,
              SlideRoute(RecordDetails(
                visitor: visitor,
              )));
        },
        onLongPress: () {
          if (SpUtil.getString("userName") == "admin") {
            showDialog(
              context: context,
              builder: (context) => AlertDialog(
                title: Text("提示"),
                content: Text(
                  "删除这条记录",
                  style: TextStyle(
                    color: Colors.red,
                  ),
                ),
                actions: [
                  TextButton(
                    onPressed: () {
                      onLongPress(index);
                      Navigator.of(context).pop();
                    },
                    child: Text("确定"),
                  ),
                  TextButton(
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                    child: Text("取消"),
                  ),
                ],
              ),
            );
          }
        },
      ),
    );
  }
}
